﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="" file="RouteExtensions.cs">
//   
// </copyright>
// <summary>
//   The route extensions.
// </summary>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace Skymate.Mvc.Extensions
{
    using System.Web.Mvc;
    using System.Web.Routing;

    using Skymate.Extensions;

    /// <summary>
    /// The route extensions.
    /// </summary>
    public static class RouteExtensions
    {
        /// <summary>
        /// The get area name.
        /// </summary>
        /// <param name="routeData">
        /// The route data.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetAreaName(this RouteData routeData)
        {
            object obj2;
            if (routeData.DataTokens.TryGetValue("area", out obj2))
            {
                return obj2 as string;
            }

            return routeData.Route.GetAreaName();
        }

        /// <summary>
        /// The get area name.
        /// </summary>
        /// <param name="route">
        /// The route.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetAreaName(this RouteBase route)
        {
            var area = route as IRouteWithArea;
            if (area != null)
            {
                return area.Area;
            }

            var route2 = route as Route;
            if ((route2 != null) && (route2.DataTokens != null))
            {
                return route2.DataTokens["area"] as string;
            }

            return null;
        }

        /// <summary>
        /// Generates an identifier for the given route in the form "[{area}.]{controller}.{action}"
        /// </summary>
        /// <param name="routeData">
        /// The route Data.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GenerateRouteIdentifier(this RouteData routeData)
        {
            var area = routeData.GetAreaName();
            var controller = routeData.GetRequiredString("controller");
            var action = routeData.GetRequiredString("action");

            return "{0}{1}.{2}".FormatInvariant(area.HasValue() ? area + "." : string.Empty, controller, action);
        }
    }
}